const HtmlWebpackPlugin = require('html-webpack-plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const CopyPlugin = require('copy-webpack-plugin')
const { resolve } = require('path')
const glob = require('glob')
const { isDev, isPro, PATH } = require('../constant')

const htmlPluginArray = []

function getEntry() {
  const entry = {}
  glob.sync('./src/pages/*/*/index.js').forEach(function (filePath) {
    var name = filePath.match(/\/pages\/(.+)\/index.js/)
    name = name[1]
    entry[name] = filePath

    htmlPluginArray.push(
      new HtmlWebpackPlugin({
        filename: './' + name + '/index.html',
        chunks: [name],
        template: './public/index.html',
      })
    )
  })
  return entry
}

const getCssLoaders = (importLoaders) => [
  isDev ? 'style-loader' : MiniCssExtractPlugin.loader,
  {
    loader: 'css-loader',
    options: {
      modules: false,
      sourceMap: isDev,
      importLoaders,
    },
  },
  {
    loader: 'postcss-loader',
    options: {
      postcssOptions: {
        plugins: [
          require('postcss-flexbugs-fixes'),
          isPro && [
            'postcss-preset-env',
            {
              autoprefixer: {
                grid: true,
                flexbox: 'no-2009',
              },
              stage: 3,
            },
          ],
        ].filter(Boolean),
      },
    },
  },
]

module.exports = {
  entry: getEntry(), 
  // entry: resolve(PATH, './src/index'), 
  cache: {
    type: 'filesystem',
    buildDependencies: {
      config: [__filename],
    },
  },
  output: {
    path: resolve(PATH, './dist'),
    clean: true,
  },
  resolve: {
    extensions: ['.jsx', '.js', '.json'],
    alias: {
      '@': resolve(PATH, './src'),
      Components: resolve(PATH, './src/components'),
      Utils: resolve(PATH, './src/utils'),
    },
  },
  module: {
    rules: [
      {
        test: /\.(jsx?|js)$/,
        loader: 'babel-loader',
        options: { cacheDirectory: true },
        exclude: /node_modules/,
      },
      {
        test: /\.css$/,
        use: getCssLoaders(1),
      },
      {
        test: /\.scss$/,
        use: [
          ...getCssLoaders(2),
          {
            loader: 'sass-loader',
            options: {
              sourceMap: isDev,
            },
          },
        ],
      },
      {
        test: [/\.gif$/, /\.jpe?g$/, /\.png$/],
        type: 'asset',
        parser: {
          dataUrlCondition: {
            maxSize: 4 * 1024,
          },
        },
      },
      {
        test: /\.(eot|svg|ttf|woff|woff2?)$/,
        type: 'asset/resource',
      },
    ],
  },
  plugins: [
    ...htmlPluginArray,
    // new HtmlWebpackPlugin({
    //   template: resolve(PATH, './public/index.html'),
    //   cache: true,
    // }), 
    new CopyPlugin({
      patterns: [
        {
          context: resolve(PATH, './public'),
          from: '*',
          to: resolve(PATH, './dist'),
          toType: 'dir',
          globOptions: {
            dot: true,
            gitignore: true,
            ignore: ['**/index.html'],
          },
        },
      ],
    }),
  ],
  externals: {
    react: 'React',
    'react-dom': 'ReactDOM',
  },
}
